import { topicApi } from '/api/topic'
import { feedApi } from '/api/feed'
import { userApi } from '/api/user'
import { GlobalData } from '/store/state'
import { checkAuth } from '/store/actions'
import { $event } from '/utils'

let preloadLock = false

Component({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    noMore: false,
    /** 播放列表 */
    list: [] as DomoFeed[],
    /** 当前播放的视频位于列表的索引 */
    currentIndex: 0,
    /** 当前播放的视频 */
    feed: {} as DomoFeed,
    /** 上个视频索引 */
    prevIndex: 0,
    logged: {} as DomoUserLogged,
    access: {},
    /** 导航条矩阵信息 */
    capsuleStyle: '',
    /** 控制循环播放的变量 */
    loop: true,
  },

  observers: {
    currentIndex(newIndex: number) {
      const oldIndex = this.data.prevIndex
      if (newIndex === oldIndex) return
      if (oldIndex === this.data.list.length - 2 && newIndex === this.data.list.length - 1) {
        this.fetchList()
      }
      preloadLock = false
      const oldVideo = wx.createVideoContext(`video-${oldIndex}`, this)
      oldVideo.pause()
      const newVideo = wx.createVideoContext(`video-${newIndex}`, this)
      newVideo.seek(0)
      newVideo.play()
      this.setData({
        prevIndex: newIndex,
        feed: this.data.list[newIndex],
      })
    },
  },

  methods: {
    async onLoad(query: PageQuery) {
      // if (!GlobalData.access.video) {
      //   wx.showToast({ title: '根据相关规定,无法播放视频', icon: 'none', duration: 1e5 })
      //   return
      // }
      const position = GlobalData.menuRect
      const { height, top, right } = position
      const left = GlobalData.clientWidth - right
      const capsuleStyle = `top: ${top}px;height: ${height}px;left: ${left}px;`
      this.setData({ access: GlobalData.access, capsuleStyle })
      const feedId = query.feedId ? +query.feedId : +query.id
      const excludeStr = query.exclude
      if (excludeStr) {
        let exclude = excludeStr.split(',').map((id) => +id)
        exclude = [...new Set(exclude)]
        this.setData!({
          exclude,
        })
      }
      this.setData({
        isFullScreen: GlobalData.isFullScreen,
        logged: GlobalData.logged || ({} as DomoUserLogged),
      })
      await this.fetchFeed(feedId)
      await this.fetchList()
      $event.on('after:comment', this, () => {
        const index = this.data.currentIndex
        this.setData({
          [`list[${index}].feed_comment_count`]: this.data.list[index].feed_comment_count + 1,
          [`feed.feed_comment_count`]: this.data.list[index].feed_comment_count + 1,
        })
      })
    },
    onShareAppMessage() {
      const feed: DomoFeed = this.data.list[this.data.currentIndex]
      return {
        title: feed.feed_content || `${feed.user.name}发布的视频`,
        imageUrl: feed.video!.cover.url,
        path: `/pages/feed/video/video?id=${this.data.feed.id}`,
      }
    },
    async fetchFeed(feedId: number) {
      try {
        const feed = await feedApi.getFeedDetail(feedId)
        this.setData!({
          feed: feed,
          list: [feed],
          currentFeedId: feed.id,
        })
      } catch (error) {
        wx.navigateBack({ delta: 1 })
      }
    },
    async fetchList() {
      if (this.data.oMore) return
      const exclude = (this.data.list as DomoFeed[]).map((f) => f.id)
      const list = await feedApi.getRandomFeeds({
        type: 'video',
        exclude_feeds: exclude,
      })
      if (!list.length) {
        this.setData({ noMore: true })
        return
      }
      this.setData({
        list: [...this.data.list, ...list],
      })
    },
    async onFollow() {
      const index = this.data.currentIndex
      const feed = this.data.list[index]
      await userApi.followUser(feed.user_id)
      wx.showToast({ title: '关注成功', icon: 'success' })
      this.setData({
        [`list[${index}].user.has_follower`]: true,
        [`feed.user.has_follower`]: true,
      })
    },
    async onLike() {
      const index = this.data.currentIndex
      const feed = this.data.feed
      if (feed.has_liked) {
        await feedApi.unlikeFeed(feed.id)
      } else {
        const res = await feedApi.likeFeed(feed.id)
        if (res.amount) {
          $event.emit('showMessage', {
            message: '点赞成功',
            amount: res.amount,
          } as GetRewardMessageReturns)
        }
      }

      this.setData({
        [`list[${index}].has_liked`]: !feed.has_liked,
        [`list[${index}].like_count`]: feed.like_count + (!feed.has_liked ? 1 : -1),
        [`feed.has_liked`]: !feed.has_liked,
        [`feed.like_count`]: feed.like_count + (!feed.has_liked ? 1 : -1),
      })
      $event.emit('after:like', this.data.list[index])
    },
    onComment() {
      const feed = this.data.list[this.data.currentIndex]
      $event.emit('showComment', { feedId: feed.id })
    },
    onProgress(event: WechatMiniprogram.CustomEvent) {
      if (preloadLock) return
      // 视频预加载
      if (this.data.currentIndex < this.data.list.length - 1) {
        const nextVideo = wx.createVideoContext(`video-${this.data.currentIndex + 1}`, this)
        const lastVideo = wx.createVideoContext(`video-${this.data.currentIndex - 1}`, this)
        nextVideo.pause()
        lastVideo.pause()
        preloadLock = true
      }
    },
    onEnd() {
      if (this.data.currentIndex >= this.data.list.length - 1) {
        wx.showToast({ title: '没有更多了', icon: 'none' })
      }
      // 如需自动播放下一个视频打开下面的注释
      // const index = Math.min(this.data.currentIndex + 1, this.data.list.length - 1)
      // this.setData!({
      //   currentIndex: index,
      // })
    },
    onSwiperChange(event: WechatMiniprogram.CustomEvent) {
      // wx.nextTick(() => {
      //   this.setData({ currentIndex: event.detail.current })
      // })
      this.setData({ currentIndex: event.detail.current })
      const nextVideo = wx.createVideoContext(`video-${this.data.currentIndex + 1}`, this)
      const lastVideo = wx.createVideoContext(`video-${this.data.currentIndex - 1}`, this)
      nextVideo.pause()
      lastVideo.pause()
    },
    onSwiperOffset() {
      wx.createVideoContext(`video-${this.data.currentIndex}`, this).play()
    },
    onReward() {
      if (!this.data.feed.topics[0]) return
      $event.emit('reward', { topicId: this.data.feed.topics[0].id })
    },
    async onFollowTopic() {
      if (!this.data.feed.topics[0]) return
      await checkAuth()
      if (this.data.feed.topics[0].has_followed) {
        await topicApi.unfollowTopic(this.data.feed.topics[0].id)
      } else {
        await topicApi.followTopic(this.data.feed.topics[0].id)
      }
      this.setData({
        [`list[${this.data.currentIndex}].topics[0].has_followed`]:
          !this.data.feed.topics[0].has_followed,
        [`feed.topics[0].has_followed`]: !this.data.feed.topics[0].has_followed,
      })
    },
    /** 圈子详情 */
    goCircleDetail() {
      if (!this.data.feed.topics[0]) return
      const id = this.data.feed.topics[0].id
      wx.navigateTo({
        url: `/pages/topic/detail/detail?id=${id}`,
      })
    },
    goBack() {
      const pages = getCurrentPages()
      if (pages.length === 1) {
        wx.switchTab({ url: '/pages/feed/list/list' })
      } else {
        wx.navigateBack({ delta: 1 })
      }
    },
    /** 跳转个人主页 */
    viewUser(e: WechatMiniprogram.CustomEvent) {
      const {
        currentTarget: {
          dataset: { userId },
        },
      } = e
      wx.navigateTo({
        url: `/mine/homePage/homePage?id=${userId}`,
      })
    },
  },
})

interface PageQuery extends WechatMiniprogram.IAnyObject {
  /** 视频动态ID */
  feedId: string
  /** 排除看过的视频动态ID */
  exclude?: string
}
